#include "DataAccess.h"

#include <string>

using namespace std;
USING_NS_CC;

// --------------------------- singleton -----------------------------

DataAccess* DataAccess::_sharedInstance = 0;

DataAccess::DataAccess()
{
    shapeData = new ShapeData();
    atexit(&purgeDataAccess);
}

DataAccess::~DataAccess()
{
    if (shapeData) {
        delete shapeData;
        shapeData = NULL;
    }
}

void DataAccess::purgeDataAccess()
{
    delete _sharedInstance;
    _sharedInstance = 0;
}

DataAccess* DataAccess::sharedDataAccess()
{
    if (_sharedInstance == 0) {
        _sharedInstance = new DataAccess();
    }
    return _sharedInstance;
}

// -------------------------- instance functions ----------------------------------
void DataAccess::loadGameData()
{
    CCUserDefault *userDefault = CCUserDefault::sharedUserDefault();

    gameData.hasSound = userDefault->getBoolForKey(HAS_SOUND, true);
    gameData.hasMusic = userDefault->getBoolForKey(HAS_MUSIC, true);
    gameData.controlType = userDefault->getIntegerForKey(CONTROL_TYPE, 0);
    gameData.selectedChapter = userDefault->getIntegerForKey(SELECTED_CHAPTER, 1);
    gameData.selectedLevel = userDefault->getIntegerForKey(SELECTED_LEVEL, 1);
}

void DataAccess::saveGameData()
{
    CCUserDefault *userDefault = CCUserDefault::sharedUserDefault();

    userDefault->setBoolForKey(HAS_SOUND, gameData.hasSound);
    userDefault->setBoolForKey(HAS_MUSIC, gameData.hasMusic);
    userDefault->setIntegerForKey(CONTROL_TYPE, gameData.controlType);
    userDefault->setIntegerForKey(SELECTED_CHAPTER, gameData.selectedChapter);
    userDefault->setIntegerForKey(SELECTED_LEVEL, gameData.selectedLevel);

    userDefault->flush();
}

void DataAccess::loadObjectShapePath(string _fileName)
{
    shapeData->initShapeData(_fileName);
}

void DataAccess::getFixturesForBody(b2Body *_body, const string &_key, const char &_filterGroup)
{
    shapeData->createFixtures(_body, _key, _filterGroup);
}
